package com.zelin;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.junit.Test;

import java.util.Date;

public class JwtTest {

    //1.创建token对象
    @Test
    public void test01(){
        //1.需要一个jwtBuilder对象
        JwtBuilder jwtBuilder=Jwts.builder()
                .setId("1024")
                .setIssuedAt(new Date())//设置发布时间
                .setSubject("admin")    //主题部分
                .signWith(SignatureAlgorithm.HS256,"zelin");//定义签名
        //2.根据buileder对象生成token字符串
        String compact = jwtBuilder.compact();
        //3.打印
        System.out.println("token字符串="+compact);
    }

    //2.解析token字符串
    @Test
    public void test02(){
        //1得到一个token字符串
        String tokenStr="eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxMDI0IiwiaWF0IjoxNTc3MTU3MjIxLCJzdWIiOiJhZG1pbiJ9.wA54ylAaq7fa-Wu-MvprlFV7GOfooxC1asrJQQfHunI";
        //2.根据jwts解析token字符串
        Claims zelin = Jwts.parser().setSigningKey("zelin").parseClaimsJws(tokenStr).getBody();
        //3.得到参数
        Date issuedAt = zelin.getIssuedAt();
        String id = zelin.getId();
        String subject = zelin.getSubject();
        //4.打印
        System.out.println("id = " + id);
        System.out.println("issuedAt = " + issuedAt);
        System.out.println("subject = " + subject);
    }

    //3.包含过期时间+参数的版本(得到token字符串)
    @Test
    public void test03(){
        //1.设置到期时间
        long l = System.currentTimeMillis();
        Date date = new Date(l + 60 * 4*1000);
        //2.构造一个jwtbuilder对象
        JwtBuilder jwtBuilder = Jwts.builder().setId("2048")
                .setIssuedAt(new Date())    //发布时间
                .setSubject("user")         //主题部分
                .signWith(SignatureAlgorithm.HS256, "zelin")
                .claim("roles","admin") //参数
                .setExpiration(date);           //到期时间
        //3.生成一个token字符串
        String compact = jwtBuilder.compact();
        //4.打印
        System.out.println("compact = " + compact);
    }

    //4.包含过期时间+参数的版本（解析token字符串）
    @Test
    public void test04(){
        //1.得到token字符串
        String tokenStr="";
        //2.设置一系列参数，得到claims对象
        Claims body = Jwts.parser().setSigningKey("zelin")
                .parseClaimsJws(tokenStr)
                .getBody();
        //3.得到一系列参数
        String id = body.getId();
        String subject = body.getSubject();
        Date issuedAt = body.getIssuedAt();
        Date expiration = body.getExpiration();
        String roles = (String) body.get("roles");
        //4.打印参数
        System.out.println("id = " + id);
        System.out.println("subject = " + subject);
        System.out.println("issuedAt = " + issuedAt);
        System.out.println("expiration = " + expiration);
        System.out.println("roles = " + roles);

    }

}
